<template>
  <el-dialog v-model="visible" title="新增下一级设备" width="95%" top="5vh">
    <!-- 可滚动区域 -->
    <div class="table-wrapper" ref="tableWrapper">
      <el-table
        :data="rows"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f9fafb', fontWeight: 600 }"
      >
        <el-table-column prop="parentName" label="上一级名称" min-width="160">
          <template #default="{ row }">
            <el-input v-model="row.parentName" placeholder="上一级名称" />
          </template>
        </el-table-column>

         

        <el-table-column prop="nodeType" label="类型" min-width="120">
  <template #default="{ row, $index }">
    <el-select v-model="row.nodeType" @change="onTypeChange($index)">
      <el-option
        v-for="opt in getTypeOptions()"
        :key="opt.value"
        :label="opt.label"
        :value="opt.value"
      />
    </el-select>
  </template>
</el-table-column> 

        <el-table-column prop="name" label="名称" min-width="150">
          <template #default="{ row }"
            ><el-input v-model="row.name"
          /></template>
        </el-table-column>

        <el-table-column prop="beType" label="类别" min-width="120">
          <template #default="{ row }"
            ><el-input v-model="row.beType"
          /></template>
        </el-table-column>

        <el-table-column prop="mokuai" label="模块" min-width="120">
          <template #default="{ row }"
            ><el-input v-model="row.mokuai"
          /></template>
        </el-table-column>

        <el-table-column prop="area" label="区域" min-width="120">
          <template #default="{ row }"
            ><el-input v-model="row.area"
          /></template>
        </el-table-column>

        <el-table-column prop="specification" label="规格" min-width="150">
          <template #default="{ row }"
            ><el-input v-model="row.specification"
          /></template>
        </el-table-column>

        <el-table-column prop="material" label="材质" min-width="120">
          <template #default="{ row }"
            ><el-input v-model="row.material"
          /></template>
        </el-table-column>

        <el-table-column prop="unit" label="单位" min-width="100">
          <template #default="{ row }"
            ><el-input v-model="row.unit"
          /></template>
        </el-table-column>

        <el-table-column prop="quantity" label="数量" min-width="120">
          <template #default="{ row }"
            ><el-input-number v-model="row.quantity" :min="0"
          /></template>
        </el-table-column>

        <el-table-column prop="amount" label="金额(万)" min-width="120">
          <template #default="{ row }"
            ><el-input-number v-model="row.amount" :min="0"
          /></template>
        </el-table-column>

        <el-table-column prop="designTemp" label="设计温度(℃)" min-width="130">
          <template #default="{ row }"
            ><el-input-number v-model="row.designTemp"
          /></template>
        </el-table-column>

        <el-table-column
          prop="designPress"
          label="设计压力(MPa)"
          min-width="130"
        >
          <template #default="{ row }"
            ><el-input-number v-model="row.designPress"
          /></template>
        </el-table-column>

        <el-table-column prop="motorPower" label="电机功率(KW)" min-width="130">
          <template #default="{ row }"
            ><el-input-number v-model="row.motorPower"
          /></template>
        </el-table-column>

        <el-table-column prop="mixingType" label="搅拌形式" min-width="120">
          <template #default="{ row }"
            ><el-input v-model="row.mixingType"
          /></template>
        </el-table-column>

        <el-table-column prop="brand" label="品牌" min-width="120">
          <template #default="{ row }"
            ><el-input v-model="row.brand"
          /></template>
        </el-table-column>

        <el-table-column prop="manufacturer" label="厂家" min-width="120">
          <template #default="{ row }"
            ><el-input v-model="row.manufacturer"
          /></template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" min-width="180">
          <template #default="{ row }"
            ><el-input v-model="row.remark"
          /></template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ $index }">
            <el-button link type="primary" @click="copyRow($index)"
              >复制</el-button
            >
            <el-button link type="warning" @click="clearRow($index)"
              >清空</el-button
            >
            <el-button link type="danger" @click="removeRow($index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部按钮 -->
    <div class="add-btn">
      <el-button type="success" plain size="small" @click="addRow"
        >＋ 新增一行</el-button
      >
      <el-button type="info" plain size="small" @click="scrollToLeft"
        >⬅ 回到最左边</el-button
      >
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, watch, nextTick } from "vue";
import { ElMessage } from "element-plus";

const emit = defineEmits(["confirm"]);

const visible = ref(false);
const rows = reactive([]);
const parentItem = ref(null);
const tableWrapper = ref(null);

const ORDER = ["SYSTEM", "MACHINE", "MODULE", "COMPONENT", "PART"];

// ✅ 缓存
const lastCache = reactive({});
const cacheKey = ref("");

// ✅ 打开弹窗
function open(item) {
  visible.value = true;
  parentItem.value = item || {};

  console.log(item)
  const key = `${item.nodeType}_${item.uid || item.id || Date.now()}`;
  cacheKey.value = key;

  if (lastCache[key] && Array.isArray(lastCache[key])) {
    const cachedRows = JSON.parse(JSON.stringify(lastCache[key]));

    // ✅ 只更新类型为子设备 (MODULE) 的行
    cachedRows.forEach((r) => {
      if (r.nodeType === "MODULE") {
        r.parentName = item.name || "";
      }
    });

    rows.splice(0, rows.length, ...cachedRows);
  } else {
    rows.splice(0, rows.length);
    console.log(item.name);
    rows.push(makeEmptyRow(item.name,item.nodeType));
  }

  // 同步缓存父级名称（仅MODULE类型）
  if (cacheKey.value && lastCache[cacheKey.value]) {
    lastCache[cacheKey.value].forEach((r) => {
      if (r.nodeType === "MODULE") {
        r.parentName = item.name || "";
      }
    });
  }

  nextTick(() => {
    rows.forEach(r => {
        if (!getTypeOptions().some(opt => opt.value === r.nodeType)) {
        r.nodeType = getTypeOptions()[0]?.value || "";
        }
    });
  });
}


function getTypeOptions() {
  const pType = parentItem.value?.nodeType || "";

  switch (pType) {
    case "MACHINE": // 如果父是母设备
      return [
        { label: "子设备", value: "MODULE" },
        { label: "部件", value: "COMPONENT" },
        { label: "零件", value: "PART" },
      ];

    case "MODULE": // 如果父是子设备
      return [
        { label: "部件", value: "COMPONENT" },
        { label: "零件", value: "PART" },
      ];

    case "COMPONENT": // 如果父是部件
      return [{ label: "零件", value: "PART" }];

    default:
      // 兜底
      return [
        { label: "子设备", value: "MODULE" },
        { label: "部件", value: "COMPONENT" },
        { label: "零件", value: "PART" },
      ];
  }
}



// ✅ 自动推导下一级类型
function nextType(type) {
  const idx = ORDER.indexOf(type);
  return ORDER[idx + 1] || "PART";
}

// ✅ 构造新行（带自动带出）
function makeEmptyRow(customParentName, forcedType) {
  const p = parentItem.value || {};
  const defaultType = forcedType || nextType(p.nodeType);
  const parentName = customParentName || p.name || "";

  const base = {
    uid: Math.random().toString(36).slice(2),
    parentName,
    nodeType: defaultType,
    code: "",
    name: "",
    beType: "",
    mokuai: "",
    area: "",
    specification: "",
    material: "",
    unit: "台",
    quantity: 0,
    amount: 0,
    designTemp: 0,
    designPress: 0,
    motorPower: 0,
    mixingType: "",
    brand: "",
    manufacturer: "",
    remark: "",
  };

  // ✅ 自动带出母设备字段
  console.log(p);
  if (p.nodeType === "MACHINE") { 
    base.mokuai = p.mokuai || "";
    base.area = p.area || "";
    base.specification = p.specification || ""; 
    base.material = p.material || ""; 
    base.unit = p.unit || ""; 
  }

  return base;
}

// ✅ 操作函数
// 从下往上找最近的指定类型（要求有非空名称）
function findNearest(type) {
  for (let i = rows.length - 1; i >= 0; i--) {
    const r = rows[i];
    if (r.nodeType === type && r.name && r.name.trim()) return r;
  }
  return null;
}

function addRow() {
  const last = rows[rows.length - 1];
  // 新行的类型按链路推进：PART 不再往下
  const next = last.nodeType === "PART" ? "PART" : nextType(last.nodeType);

  let parentName = parentItem.value?.name || "";
  // 👇 父级只看“新行类型”来决定
  if (next === "MODULE") {
    // 子设备的父级：上一行(或最近)的名称（一般是父节点或同级）
    parentName = last.name?.trim() || parentItem.value?.name || "";
  } else if (next === "COMPONENT") {
    // 部件的父级：最近的子设备
    const mod = findNearest("MODULE");
    parentName = mod ? mod.name : (parentItem.value?.name || "");
  } else if (next === "PART") {
    // 零件的父级：最近的部件；没有部件再找最近的子设备
    const comp = findNearest("COMPONENT");
    if (comp) {
      parentName = comp.name;
    } else {
      const mod = findNearest("MODULE");
      parentName = mod ? mod.name : (parentItem.value?.name || "");
    }
  }

  rows.push(makeEmptyRow(parentName, next));
}

function onTypeChange(index) {
  const r = rows[index];
  if (!r) return;

  // 默认：父级名称继承上一级或当前父节点
  let parentName = parentItem.value?.name || "";

  // 工具函数：从下往上找最近的指定类型
  const findNearest = (type) => {
    for (let i = index - 1; i >= 0; i--) {
      const x = rows[i];
      if (x.nodeType === type && x.name && x.name.trim()) return x;
    }
    return null;
  };

  // ✅ 根据选中类型决定“上一级名称”
  switch (r.nodeType) {
    case "MODULE": {
      // 子设备 → 上一级是当前父节点
      parentName = parentItem.value?.name || "";
      break;
    }
    case "COMPONENT": {
      // 部件 → 最近的子设备
      const mod = findNearest("MODULE");
      parentName = mod ? mod.name : parentItem.value?.name || "";
      break;
    }
    case "PART": {
      // 零件 → 最近的部件，没有就找最近的子设备
      const comp = findNearest("COMPONENT");
      if (comp) {
        parentName = comp.name;
      } else {
        const mod = findNearest("MODULE");
        parentName = mod ? mod.name : parentItem.value?.name || "";
      }
      break;
    }
  }

  // ✅ 更新当前行的上一级名称
  r.parentName = parentName;
}



function removeRow(i) {
  rows.splice(i, 1);
  if (!rows.length) addRow();
}

function copyRow(i) {
  const newRow = JSON.parse(JSON.stringify(rows[i]));
  newRow.uid = Math.random().toString(36).slice(2);
  rows.splice(i + 1, 0, newRow);
}

function clearRow(i) {
  const type = rows[i].nodeType;
  const parentName = rows[i].parentName;
  rows[i] = makeEmptyRow(parentName, type);
}

function scrollToLeft() {
  nextTick(() => {
    if (tableWrapper.value) tableWrapper.value.scrollLeft = 0;
  });
}

// ✅ 确认（校验 + 缓存）
function confirm() {
  for (let i = 0; i < rows.length; i++) {
    const r = rows[i];
    if (!r.parentName?.trim() || !r.name?.trim()) {
      return ElMessage.error(`第 ${i + 1} 行：上一级名称和名称不能为空`);
    }
  }

  if (cacheKey.value) {
    lastCache[cacheKey.value] = JSON.parse(JSON.stringify(rows));
  }

  emit("confirm", JSON.parse(JSON.stringify(rows)));
  visible.value = false;
}

// ✅ 监听关闭也缓存
watch(visible, (val) => {
  if (!val && cacheKey.value) {
    lastCache[cacheKey.value] = JSON.parse(JSON.stringify(rows));
  }
});

defineExpose({ open });
</script>

<style scoped>
.table-wrapper {
  overflow-x: auto;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}
.add-btn {
  text-align: right;
  padding: 10px;
  background: #fafafa;
  border-top: 1px solid #ebeef5;
}
</style>